﻿using Guoc.BigMall.Infrastructure.Log;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Guoc.BigMall.Infrastructure.Payment.Wechat
{
    public class WechatGetway : IWechatGetway
    {
        WechatConfig _config;
       

        public string StoreCode { get => _config.StoreCode; }

      

        public WechatGetway(WechatConfig config)
        {
            this._config = config;
           
        }

        public WechatConfig Config
        {
            get
            {
                return this._config;
            }
        }

        #region JSAPI 支付

        /// <summary>
        /// <para>微信统一下单接口：URL地址：https://api.mch.weixin.qq.com/pay/unifiedorder </para>
        /// <para>doc ：https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1 </para>
        /// <para>openid</para>
        /// <para>out_trade_no：商户系统内部订单号，要求32个字符内，只能是数字、大小写字母</para>
        /// <para>total_fee：订单总金额，单位为分</para>
        /// <para>body ：商品简单描述</para>
        /// <para>trade_type ：JSAPI，NATIVE ，APP</para>
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public PayResult UnifiedOrder(PayRequest data)
        {
            ILogger _log = AppContext.Current.Resolve<ILogger>();
            //1  传递参数
            var url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            // 统一下单必填校验
            data.CheckRequired("out_trade_no");
            data.CheckRequired("body");
            data.CheckRequired("total_fee");
            data.CheckRequired("trade_type");
            data.CheckRequired("openid");

            //附加商户参数
            data.Add("notify_url", _config.NotifyUrl);
            data.Add("appid", _config.AppId);
            data.Add("mch_id", _config.MchId);
            //data.Add("spbill_create_ip", "39.99.177.60"); //终端ip
            data.Add("nonce_str", data.GenerateNonceStr());
            data.Add("sign_type", PayRequest.SIGN_TYPE_MD5);
            data.Add("sign", data.MakeSign(PayRequest.SIGN_TYPE_MD5, _config.MchKey));
            int timeout = 6;
            var xml = data.ToXml();
            _log.Info("微信统一下单请求报文:");
            _log.Info(xml);
            string response = HttpService.Post(xml, url, false, timeout);
            _log.Info("微信响应报文:");
            _log.Info(response);
            PayResult result = new PayResult();
            result.FromXml(response);

            if (result.Content["return_code"].ToString() == "FAIL" || result.Content["result_code"].ToString() == "FAIL")
            {
                throw new FriendlyException(string.Format("微信统一下单失败:{0}", result.Content["return_msg"]));
            }

            // 校验 js 必须的参数
            result.CheckRequired("appid");
            result.CheckRequired("prepay_id");
            // 校验签名
            result.CheckSign(PayRequest.SIGN_TYPE_MD5, _config.MchKey);

            return result;
        }



        /// <summary>
        /// <para>微信统一下单接口：URL地址：URL地址：https://api.mch.weixin.qq.com/pay/orderquery </para>
        /// <para>doc ：https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_2 </para>
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>

        public PayResult OrderQuery(PayRequest request)
        {
            return null;
        }

        /// <summary>
        ///  转账到个人零钱
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public PayResult Transfers(PayRequest data)
        {
            ILogger _log = AppContext.Current.Resolve<ILogger>();
            var url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";

            // 附加账号参数
            data.Add("mch_appid", _config.AppId);
            data.Add("mchid", _config.MchId);
            data.Add("nonce_str", data.GenerateNonceStr());
           // data.Add("sign_type", PayRequest.SIGN_TYPE_MD5);
            data.Add("sign", data.MakeSign(PayRequest.SIGN_TYPE_MD5, _config.MchKey));

            int timeout = 6;
            var xml = data.ToXml();
            _log.Info("微信转账到个人:");
            _log.Info(xml);
            // 使用证书
            HttpService.SSlCertPath = _config.SSlCertPath;  // 证书路径
            HttpService.SSlCertPassword = _config.MchId;  // 证书初始密码就是商户号
            string response = HttpService.Post(xml, url, true, timeout);
            _log.Info("微信响应报文:");
            _log.Info(response);
            PayResult result = new PayResult();
            result.FromXml(response);

            if (result.Content["return_code"].ToString() == "FAIL" || result.Content["result_code"].ToString() == "FAIL")
            {
                throw new FriendlyException(string.Format("微信转账到个人失败:{0}", result.Content["return_msg"]));
            }

            // 校验 js 必须的参数
            result.CheckRequired("mch_appid");
            // 校验签名
            result.CheckSign(PayRequest.SIGN_TYPE_MD5, _config.MchKey);

            return result;
        }


        #endregion


    }
}
